// 瀑布流高度计算
wx.computeWaterfall = async (option) => {
  let {
    list,
    colH1,
    colH2,
    key
  } = option;
  let RANDOM_HEIGHT = [126, 136, 146];
  let col1 = [],
    col2 = [];
  return new Promise((resolve) => {
    wx.getSystemInfo({
      success: res => {
        const W = res.windowWidth * 0.45;
        const REM = res.windowWidth / 750;
        const H = res.windowHeight;
        const barHeight = REM * 180 // 信息栏的高度
        list.map(item => {
          let imgHeight;
          if (!item.hasOwnProperty('attach')) {
            item['attach'] = item.attachment
          }
          if (item[key] && JSON.stringify(item[key]) != '{}') {
            const {
              fheight,
              fwidth
            } = item[key];
            if (fheight > 0 && fwidth > 0) {
              let scale = W / fwidth;
              imgHeight = fheight * scale; // 自适应高度
              let maxHeight = H * .50; // 限制最大高度
              imgHeight > maxHeight && (imgHeight = maxHeight);
              // imgHeight < 126 && (imgHeight = RANDOM_HEIGHT[parseInt(Math.random() * (2 - 0 + 1) + 0, 10)])
              imgHeight < 126 && (imgHeight = REM * 252) // 限制最低高度
            } else {
              imgHeight = W;
            }
          } else {
            imgHeight = W;
          }
          item.height = imgHeight;
          let totalH = imgHeight + barHeight;
          if (colH1 <= colH2) {
            colH1 += totalH;
            col1.push(item);
          } else {
            colH2 += totalH;
            col2.push(item);
          }
        });
        resolve({
          colH1,
          colH2,
          col1,
          col2
        })
      }
    })
  })
}
wx.imgLoadError = function (key) {
  this.setData({
    [key]: "https://zwmj.oss-cn-shanghai.aliyuncs.com/xcx/1.0/img/defaultAvatar.png"
  })
}
wx.mergeGalleryArr = function (oldArr, newArr) {
  const i = oldArr.length - 1;
  if (i >= 0 && oldArr[i].group_name == newArr[0].group_name) {
    oldArr[i].thumb_files = [...oldArr[i].thumb_files, ...newArr[0].thumb_files];
    newArr.shift();
  };
  return {
    oldArr,
    newArr
  }
}
// 获取单个类名Dom信息
wx._getElement = function (a) {
  return new Promise((resolve) => {
    const query = wx.createSelectorQuery()
    query.select(a).boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (o) {
      resolve(o)
    })
  })
}
// 一次获取多个类名Dom信息
wx._getElementAll = function (a) {
  return new Promise((resolve) => {
    const query = wx.createSelectorQuery()
    query.selectAll(a).boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (o) {
      resolve(o)
    })
  })
}

String.prototype.colorRgb = function () {
  // 16进制颜色值的正则
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 把颜色值变成小写
  var color = this.toLowerCase();
  if (reg.test(color)) {
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      var colorNew = "#";
      for (var i = 1; i < 4; i += 1) {
        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
      }
      color = colorNew;
    }
    // 处理六位的颜色值，转为RGB
    var colorChange = [];
    for (var i = 1; i < 7; i += 2) {
      colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
    }
    return colorChange.join(",");
  } else {
    return color;
  }
}

wx.ArrSplit = (arr, n) => {
  let b = [];
  let result = [];
  let k = 0;
  for (let i = 0; i < arr.length; i++) {
    if (i % n == 0) {
      b = [];
      for (var j = 0; j < n; ++j) {
        if (arr[i + j] == undefined) {
          continue;
        } else {
          b[j] = arr[i + j];
        }
      }
      result[k] = b;
      k++;
    }
  }
  return result;
}

/**
 * 检查路由栈中是否包含某个路由
 * @param {String} routeName 路由名称（在app.json中的全名称） 
 * 
 * @return {
 *  have:true,  //当前路由栈是否包含传入的路由
 *  index:0     //此路由在路由栈中的索引，(可用wx.navigateBack返回)
 * }
 */
wx.checkIncludeRoute = (routeName) => {
  let result = {
    have: false,
    index: 0
  };
  let route = getCurrentPages();
  for (let a = 0; a < route.length; a++) {
    if (route[a].route === routeName) {
      result = {
        have: true,
        index: (route.length - 1) - a
      };
      break;
    }
  }
  return result;
}


/**
 * 判断上一个页面路由是否为某个路由名称
 * @param {String} routeName 路由名称（在app.json中的全名称） 
 * 
 * @return {
 *  have:true,  //当前路由栈是否包含传入的路由
 *  index:0     //此路由在路由栈中的索引，(可用wx.navigateBack返回)
 * }
 */
wx.lastPageName = (routeName) => {
  let route = getCurrentPages();
  if (route.length > 1) {
    return routeName == route[route.length - 2].route;
  }
  return false;
}

/**
 * 判断当前路由是否为某个路由名称
 * @param {String} routeName 路由名称（在app.json中的全名称） 
 * 
 * @return {
 *  have:true,  //当前路由栈是否包含传入的路由
 *  index:0     //此路由在路由栈中的索引，(可用wx.navigateBack返回)
 * }
 */
wx.currentPageName = (routeName) => {
  let route = getCurrentPages();
  if (route.length > 0) {
    return routeName == route[route.length - 1].route;
  }
  return false;
}

/**
 * 给有‘原价’标签的项目item增加标识
 * @param {Array} items 包含得有labels字段的数组 [{labels:["套餐优惠", "局麻", "0.5小时"]}]
 */
wx.checkOriginalPrice = (items) => {
  return new Promise((resolve) => {
    let newLabels = [],
      obj = {};
    items.map(item => {
      newLabels = []
      if (item.labels && item.labels.length > 0) {
        item.labels.map(_item => {
          obj = {};
          obj.text = _item;
          if (/^原价/.test(_item)) {
            obj.have_originalPrice = true;
          }
          newLabels.push(obj);
        })
      }
      item.newLabels = newLabels;
    })
    resolve(items);
  })
}


//判断是否为底部有黑线的iPhone
// 手机是否有底部横条（通过返回的safeArea安全高度 > 20 判断是否有刘海屏，有刘海屏则有底部横条）
wx.isIphone = () => {
  let info = wx.getSystemInfoSync();
  // if (/iphone\sx/i.test(info.model) || (/iphone/i.test(info.model) && /unknown/.test(info.model)) || /iphone\s11/i.test(info.model)) {
  if (info.safeArea.top > 20 && (/iphone/i.test(info.model) || /unknown/.test(info.model))) {
    return true;
  } else {
    return false;
  }
}
wx.isEmpty = (str) => {
  return (str === null || str === "" || str === undefined || JSON.stringify(str) === "{}" || str == 'undefined' || str.length == 0);
}

/**
 * 判断预约类型单一
 * @param {Object} opts 
 * @param {Array} list 预约类型数组
 * @param {Number} type 要判定的类型
 * return boolean
 */
wx.onlyFaceDiagnose = (opts) => {
  const {
    list,
    type
  } = opts;
  for (let a = 0; a < list.length; a++) {
    if (list[a] != type) {
      return false
    }
  }
  return true
}

/**
 * 统计各个预约类型的个数
 * @param {Array} list 项目列表
 * @param {String} key 选中项的key
 * 
 */
wx.statisticalBookingTypeCount = (opts) => {
  const {
    list,
    key
  } = opts;
  let a = 0,
    b = 0,
    c = 0,
    d = 0;
  //is_faceseeing： 项目类型，0-治疗+面诊；1-面诊；2-直播半价；3-先做后付
  if (list.length > 0) {
    list.map(item => {
      if (key) {
        if (item[key]) {
          switch (parseInt(item.is_faceseeing)) {
            case 0:
              a++;
              break;
            case 1:
              b++;
              break;
            case 2:
              c++;
              break;
            case 3:
              d++;
              break;
          }
        }
      } else {
        switch (parseInt(item.is_faceseeing)) {
          case 0:
            a++;
            break;
          case 1:
            b++;
            break;
          case 2:
            c++;
            break;
          case 3:
            d++;
            break;
        }
      }
    })
  }
  return {
    cure: a,
    face: b,
    live: c,
    later: d,
  }
}